package com.yaorange.module.system.service.impl;

import com.yaorange.module.system.entity.vo.PermissionTreeVO;
import com.yaorange.module.system.repository.SysPermissionRepository;
import com.yaorange.module.system.service.SysPermissionService;
import com.yaorange.pojo.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;

@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Autowired
    private SysPermissionRepository sysPermissionRepository;

    @Override
    public List<PermissionTreeVO> findPermissionsTree() {
        // 获取所有权限
        List<SysPermission> sysPermissionList = sysPermissionRepository.selectPermissions();

        if (sysPermissionList == null || sysPermissionList.isEmpty()) {
            return new ArrayList<>();
        }

        // 创建Map，用于封装权限对象
        HashMap<Long, PermissionTreeVO> treeVOMap = new HashMap<>();
        // 遍历 权限集合
        for (int i = 0; i < sysPermissionList.size(); i++) {
            SysPermission sysPermission = sysPermissionList.get(i);
            PermissionTreeVO permissionTreeVO = new PermissionTreeVO();
            permissionTreeVO.setId(sysPermission.getPermId());
            permissionTreeVO.setLabel(sysPermission.getPermTitle());
            permissionTreeVO.setChildren(new ArrayList<>());
            treeVOMap.put(sysPermission.getPermId(), permissionTreeVO);
        }

        // 构建权限树
        List<PermissionTreeVO> rootTreeVo = new ArrayList<>();
        for(SysPermission sysPermission:sysPermissionList){
            // pid是null 则代表是父节点
            if(sysPermission.getPermPid() == null){
                PermissionTreeVO parentVo = treeVOMap.get(sysPermission.getPermId());
                rootTreeVo.add(parentVo);
            }else{
                // 子节点
                PermissionTreeVO parentVo = treeVOMap.get(sysPermission.getPermPid());
                parentVo.getChildren().add(treeVOMap.get(sysPermission.getPermId()));
            }
        }
        return rootTreeVo;
    }

    @Override
    public List<SysPermission> findPermissionsTreeByUserId(Long sysId) {
        List<SysPermission> sysPermissionList = sysPermissionRepository.selectPermissionsByUserId(sysId);
        return sysPermissionList;
    }


}
